package com.future.service.impl;

import com.future.service.BaiDuAIService;
import com.future.utils.Base64Util;
import com.future.utils.FileUtil;
import com.future.utils.HttpUtil;
import com.future.utils.JacksonUtil;
import com.future.dto.BaiDuAIRequestInfoDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Service
public class BaiDuAIServiceImpl implements BaiDuAIService {

    @Autowired
    private BaiDuAIRequestInfoDto baiDuAIRequestInfoDto;

    @Override
    public String getAccessToken() throws IOException {
        // 获取access_token的完整请求地址
        String url = baiDuAIRequestInfoDto.getGetURLOfAccessToken()
                + "?grant_type=" + baiDuAIRequestInfoDto.getGetGrantTypeOfAccessToken()
                + "&client_id=" + baiDuAIRequestInfoDto.getAPIKey()
                + "&client_secret=" + baiDuAIRequestInfoDto.getSecretKey();

        String result = HttpUtil.get(url);

        // 返回access_token
        return JacksonUtil.jsonNodeOf(result, "access_token").asText();
    }

    /**
     * 图片检测
     * @param image
     * @param url 百度AI接口的请求url
     * @return
     * @throws Exception
     */
    @Override
    public String check(File image, String url) throws Exception {
        String filePath = image.getPath();
        byte[] imgData = FileUtil.readFileByBytes(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String params = "image=" + imgParam;

        String result = HttpUtil.post(url, baiDuAIRequestInfoDto.getAccessToken(), params);

        // 获取result失败
        int errorCode = JacksonUtil.jsonNodeOf(result, "error_code").asInt();
        if (errorCode == 110 || errorCode == 100) {
            // 重新获取accessToken
            baiDuAIRequestInfoDto.setAccessToken(getAccessToken());
            // 重新向百度AI发送请求
            result = HttpUtil.post(url, baiDuAIRequestInfoDto.getAccessToken(), params);
        }

        return result;
    }
}
